package com.sa.nfcwriter;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Locale;

import android.content.Intent;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;

public class NFCWrite {

	private boolean ndefFormatable;
	private boolean ndef;
	private Tag tagFromIntent;

	public NFCWrite(Intent intent) {
		tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
		for (String tech : tagFromIntent.getTechList()) {
			if (tech.equals(Ndef.class.getName())) {

				ndef = true;
			} else if (tech.equals(NdefFormatable.class.getName())) {

				ndefFormatable = true;
			}
		}
	}

	public void write(final String text, final Locale locale,
			boolean encodeInUtf8) throws IOException, FormatException {
		NdefRecord mimeRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
				"application/com.sa.app".getBytes(Charset.forName("UTF-8")),
				new byte[0], text.getBytes(Charset.forName("UTF-8")));

		NdefRecord[] records = { mimeRecord,
				NdefRecord.createApplicationRecord("com.sa.app") };
		NdefMessage message = new NdefMessage(records);

		if (ndef) {
			Ndef ndef = Ndef.get(tagFromIntent);
			try {
				ndef.connect();
				ndef.writeNdefMessage(message);
			} finally {
				try {
					ndef.close();
				} catch (Exception ignored) {
				}
			}
		} else if (ndefFormatable) {
			NdefFormatable ndefFormatable = NdefFormatable.get(tagFromIntent);
			try {
				ndefFormatable.connect();
				ndefFormatable.format(message);
			} finally {
				try {
					ndefFormatable.close();
				} catch (Exception ignored) {
				}
			}
		}
	}

	public static NdefRecord newTextRecord(String text, Locale locale,
			boolean encodeInUtf8) {
		byte[] langBytes = locale.getLanguage().getBytes(
				Charset.forName("UTF-8"));

		Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset
				.forName("UTF-16");
		byte[] textBytes = text.getBytes(utfEncoding);

		int utfBit = encodeInUtf8 ? 0 : (1 << 7);
		char status = (char) (utfBit + langBytes.length);

		byte[] data = new byte[1 + langBytes.length + textBytes.length];
		data[0] = (byte) status;
		System.arraycopy(langBytes, 0, data, 1, langBytes.length);
		System.arraycopy(textBytes, 0, data, 1 + langBytes.length,
				textBytes.length);

		return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT,
				new byte[0], data);
	}
}
